<template>
  <div>
    <el-tabs tab-position="top">
      <el-tab-pane label="我的设备">
        <el-table
          stripe
          :data="myDeviceList"
          style="width: 100%">
          <el-table-column sortable label="设备ID">
            <template slot-scope="scope">
              {{ scope.row.deviceId }}
            </template>
          </el-table-column>
          <el-table-column label="设备名前缀">
            <template slot-scope="scope">
              {{ scope.row.clientPrefix }}
            </template>
          </el-table-column>
          <el-table-column label="主题">
            <template slot-scope="scope">
              {{ scope.row.topic }}
            </template>
          </el-table-column>
          <el-table-column label="生成数据坐标中心">
            <template slot-scope="scope">
              {{ scope.row.initLon }},{{ scope.row.initLat }}
            </template>
          </el-table-column>

          <el-table-column label="是否开启">
            <template slot-scope="scope">
              {{ scope.row.active ? "true" : "false" }}
            </template>
          </el-table-column>


          <el-table-column label="操作" fixed="right">
            <template slot-scope="scope">
              <el-button
                @click="alter(scope.row)"
                size="mini">编辑
              </el-button>
              <el-button
                size="mini"
                v-if="!scope.row.active"
                type="success"
                @click="startDevice(scope.row)"
              >开启
              </el-button>
              <el-button
                size="mini"
                v-if="scope.row.active"
                @click="stopDevice(scope.row)"
              >停止
              </el-button>
              <el-button
                size="mini"
                type="danger"
                @click="deleteDevice(scope)"
              >删除
              </el-button>

            </template>
          </el-table-column>

        </el-table>
      </el-tab-pane>
      <el-tab-pane label="新增设备">
        <el-form style="width: 80%;margin:0 auto;padding: 3%;" label-position="top"
                 :model="deviceForm"
                 ref="deviceFormDom"
                 :rules="deviceRules"
        >
          <el-form-item label="设备名前缀（设备名为前缀+用户ID）" prop="clientPrefix" required>
            <el-input v-model="deviceForm.clientPrefix"></el-input>
          </el-form-item>
          <el-form-item label="设备广播主题" prop="topic" required>
            <el-input v-model="deviceForm.topic"></el-input>
          </el-form-item>
          <el-form-item label="生成数据坐标中心（经纬度，默认在杭州）">
            <el-row>
              <el-col :span="12" class="filterItem">
                <el-input v-model="deviceForm.initLon" placeholder="经度"></el-input>
              </el-col>
              <el-col :span="12" class="filterItem">
                <el-input v-model="deviceForm.initLat" placeholder="纬度"></el-input>
              </el-col>
            </el-row>
          </el-form-item>
          <el-form-item label="设备是否开启">
            <el-switch v-model="deviceForm.active"></el-switch>
          </el-form-item>
          <div style="float: right;">
            <el-button>重置</el-button>
            <el-button type="success" @click="submit">提交</el-button>
          </div>
        </el-form>

      </el-tab-pane>
      <el-tab-pane label="所有设备查看">
        <el-table
          stripe
          :data="allDeviceList"
          style="width: 100%">
          <el-table-column sortable label="设备ID">
            <template slot-scope="scope">
              {{ scope.row.deviceId }}
            </template>
          </el-table-column>
          <el-table-column label="设备名前缀">
            <template slot-scope="scope">
              {{ scope.row.clientPrefix }}
            </template>
          </el-table-column>
          <el-table-column label="主题">
            <template slot-scope="scope">
              {{ scope.row.topic }}
            </template>
          </el-table-column>
          <el-table-column label="生成数据坐标中心">
            <template slot-scope="scope">
              {{ scope.row.initLon }},{{ scope.row.initLat }}
            </template>
          </el-table-column>

          <el-table-column label="是否开启">
            <template slot-scope="scope">
              {{ scope.row.active ? "true" : "false" }}
            </template>
          </el-table-column>
        </el-table>
      </el-tab-pane>
      <el-tab-pane
        label="设备信息查询"
      >
        <div>
          <el-input style="width: 30%;margin-left: 4%;" placeholder="输入设备ID以查询" v-model="targetId"></el-input>
          <el-button type="primary" style="margin-left: 4%;" @click="detailDataReq">查询</el-button>
          <el-divider></el-divider>
          <el-table
            stripe
            :data="deviceDataView"
            style="width: 100%">
            <el-table-column type="expand">
              <template slot-scope="scope">
                <el-form label-position="left">
                  <el-form-item label="生成时间">
                    {{ new Date(scope.row.timestamp).toLocaleString() }}
                  </el-form-item>
                  <el-form-item label="数据信息">
                    {{ scope.row.info }}
                  </el-form-item>
                </el-form>
              </template>
            </el-table-column>
            <el-table-column sortable label="主题">
              <template slot-scope="scope">
                {{ scope.row.topic }}
              </template>
            </el-table-column>
            <el-table-column sortable label="值">
              <template slot-scope="scope">
                {{ scope.row.value }}
              </template>
            </el-table-column>
            <el-table-column label="生成数据坐标">
              <template slot-scope="scope">
                {{ scope.row.lon }},{{ scope.row.lat }}
              </template>
            </el-table-column>
            <el-table-column sortable label="是否告警">
              <template slot-scope="scope">
                {{ scope.row.alert === 1 ? "是" : "否" }}
              </template>
            </el-table-column>
          </el-table>
          <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page.sync="curPage"
            :page-sizes="[10,50,100,200]"
            :page-size.sync="curSize"
            layout="sizes, prev, pager, next"
            style="float: right;"
            :total="deviceDataList.length">
          </el-pagination>
        </div>
      </el-tab-pane>
    </el-tabs>
    <el-dialog
      title="修改设备信息"
      :visible.sync="alterDisplay"
      :close-on-click-modal="false"
      width="50%"
    >
      <div>
        <el-form :model="curAlter"
        >
          <el-form-item label="用户名前缀">
            <el-input v-model="curAlter.clientPrefix" placeholder="小于64位的正确邮件格式"></el-input>
          </el-form-item>
          <el-form-item label="初始数据生成坐标(经度，纬度)">
            <el-input type="number"
                      @change="(val)=>{this.curAlter.initLon = parseFloat(val)}"
                      style="margin:2%"
                      v-model="curAlter.initLon" placeholder="2-15位中英文或数字"></el-input>
            <el-input type="number"
                      @change="(val)=>{this.curAlter.initLat = parseFloat(val)}"
                      style="margin:2%"
                      v-model="curAlter.initLat" placeholder="2-15位中英文或数字"></el-input>
          </el-form-item>
          <el-form-item label="当前暂时不支持修改设备topic">
            <el-input disabled v-model="curAlter.topic"></el-input>
          </el-form-item>
        </el-form>
      </div>
      <el-button type="primary" @click="regSubmit">确定</el-button>
      <el-button @click="">取消</el-button>

    </el-dialog>
  </div>
</template>

<script>

import axios from 'axios'
import qs from 'qs'
import Vue from 'vue';
import state from '../store/index'


export default {
  name: "Config",
  beforeRouteLeave(to, from, next) {
    if (this.hasLogin) {
      next(true)
    } else {
      next(vm => {    // 通过参数 `vm` 访问组件实例
        this.$message.warning("请勿在未登录的情况下强制输入路由")
        vm.$router.push('/') // 返回首页
      })
    }
  },
  mounted() {
    this.loadSelfDevices()
    this.loadAllDevices()
  },
  computed: {
    userInfo() {
      return state.getters.userInfo
    },
    deviceDataView() {
      return this.deviceDataList.slice(
        (this.curPage - 1) * this.curSize,
        this.curPage * this.curSize
      )
    },
    hasLogin() {
      return state.getters.hasLogin
    },

  },
  data() {
    return {

      deviceDataList: [],
      targetId: null,
      curPage: 1,
      curSize: 10,


      alterDisplay: false,
      curAlter: {},
      backUp: {},
      myDeviceList: [],
      allDeviceList: [],
      deviceForm: {
        ownerId: null,
        clientPrefix: null,
        initLat: null,
        initLon: null,
        active: true,
        topic: null,
      },
      deviceRules: {
        clientPrefix: [
          {
            required: true,
            validator: (rule, value, callback) => {
              const reg = /^[0-9a-zA-Z.\u4e00-\u9fa5]{1,32}$/;
              if (reg.test(value)) {
                callback()
              } else {
                callback(new Error("请输入正确格式的前缀名"))
              }
              callback()
            }, message: '请输入正确的前缀名', trigger: 'blur'
          }
        ],
        topic: [
          {
            required: true,
            validator: (rule, value, callback) => {
              const reg = /^[0-9a-zA-Z.\u4e00-\u9fa5]{1,64}$/;
              if (reg.test(value)) {
                callback()
              } else {
                callback(new Error("请输入正确格式的topic"))
              }
              callback()
            }, message: '请输入正确的topic', trigger: 'blur'
          }
        ],

      },
    }
  },
  methods: {

    handleSizeChange(val) {
      console.log(`每页 ${val} 条`);
    },
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`);
    },
    detailDataReq() {
      const id = parseInt(this.targetId)
      axios.get('/api/getDataBySender', {
        params: {
          sender: id
        }
      }).then(res => {
        if (res.data.success) {
          this.$message.success(res.data.info)
          this.deviceDataList = res.data.data
        }
      }).catch(err => {
        console.log(err)
      })
    },

    findDeviceIndex(arr, item) {
      return arr.indexOf(item)
    },

    stopDevice(row) {
      axios.post('/api/stopDevice', row).then(res => {
        if (res.data.success) {
          this.$message.success(res.data.info)
          row.active = false;
        }
      }).catch(err => {
        console.log(err)
      })
    },
    startDevice(row) {
      axios.post('/api/startDevice', row).then(res => {
        if (res.data.success) {
          this.$message.success(res.data.info)
          row.active = true;
        }
      }).catch(err => {
        console.log(err)
      })
    },
    deleteDevice(scope) {
      axios.post('/api/deleteDevice', scope.row).then(res => {
        if (res.data.success) {
          this.$message.success(res.data.info)
          Vue.delete(this.myDeviceList, this.findDeviceIndex(this.myDeviceList, scope.row))
        }
      }).catch(err => {
        console.log(err)
      })
    },

    async loadSelfDevices() {
      await axios.get('/api/getDevicesByOwnerId', {
        params: {
          ownerId: this.userInfo.id
        }
      }).then(res => {
        console.log(res)
        this.myDeviceList = res.data.data;
      }).catch(err => {
        console.log(err)
      })
    },

    loadAllDevices() {
      axios.get('/api/getAllDevices').then(res => {
        this.allDeviceList = res.data.data
      }).catch(err => {
        console.log(err)
      })
    },


    regSubmit() {
      axios.post('/api/alterDevice', this.curAlter).then(res => {
        console.log(res);
        this.loadSelfDevices();
        this.loadAllDevices()
        this.$message.success(res.data.info);
        this.alterDisplay = false;
      })

    },


    alter(data) {
      this.curAlter = this.$global.deepCopy(data)
      this.alterDisplay = true
    },

    submit() {
      this.$refs.deviceFormDom.validate(valid => {
        if (valid) {
          var postObj = JSON.parse(JSON.stringify(this.deviceForm));
          postObj.ownerId = typeof (this.userInfo.id) === "string" ? parseInt(this.userInfo.id) : this.userInfo.id;
          postObj.isActive = postObj.active ? "true" : "false";

          if (postObj.initLat != null && typeof (postObj.initLat) === 'string') {
            if (postObj.initLat.length !== 0) {
              postObj.initLat = parseFloat(postObj.initLat)
            } else {
              postObj.initLat = null;
            }
          }
          if (postObj.initLon != null && typeof (postObj.initLon) === 'string') {
            if (postObj.initLon.length !== 0) {
              postObj.initLon = parseFloat(postObj.initLon)
            } else {
              postObj.initLon = null;
            }
          }
          console.log(postObj);
          axios.get("/api/addDevice", {
            params: postObj
          })
            .then(res => {
              if (res.data.success) {
                this.$message.success(res.data.info)
              }
              axios.get('/api/getDevicesByOwnerId', {
                params: {
                  ownerId: this.userInfo.id
                }
              }).then(res => {
                this.myDeviceList = res.data.data;
              }).catch(err => {
                console.log(err)
              })
            })
            .catch(err => {
              console.log(err)
            })

        } else {
          this.$message.error("表单错误，请重新验证")
        }
      })
    },

  },
}
</script>

<style scoped>
.filterItem {
  padding-right: 4%;
}


.el-table .warning-row {
  background: oldlace;
}

.el-table .success-row {
  background: #f0f9eb;
}
</style>
